package com.blog.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.config.BlogConfig;
import com.blog.entity.SysRole;
import com.blog.entity.SysUser;
import com.blog.exception.LoginExistsException;
import com.blog.mapper.SysMenuMapper;
import com.blog.mapper.SysUserMapper;
import com.blog.service.SysUserService;
import com.blog.util.DateFormatUtil;
import com.blog.util.StringUtil;
import com.blog.util.dto.AjaxResult;
import com.blog.util.md5.MD5Util;
import com.blog.util.uuid.UUIDUtils;
import com.blog.util.xmSelect.XmSelectData;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author cgx
 * @Date 2021/8/16 22:34
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {


    @Resource
    SysUserMapper userMapper;

    @Resource
    SysMenuMapper menuMapper;

    @Override
    public SysUser login(String username, String password) throws Exception{
        SysUser sysUser = new SysUser();
        try{
            sysUser = userMapper.getUserByName(username);
        }catch (Exception e){
            sysUser = null;
        }

        if (sysUser == null){
            throw new LoginExistsException("用户不存在","userIsNotExist");
        }
        if (password.isEmpty()){
            throw new LoginExistsException("密码为空","passwordIsEmpty");
        }
        if (!password.equals(sysUser.getPassword())){
            throw new LoginExistsException("密码错误","passwordError");
        }
        return sysUser;
    }

    @Override
    public AjaxResult parseExcelData(Workbook workbook, String[] headers) {
        AjaxResult dto = new AjaxResult();
        List<SysUser> userList = new ArrayList<>();
        //获取第一个sheet(系统只允许有一个sheet，多个sheet只读取第一个)
        Sheet sheet = workbook.getSheetAt(0);
        //获取行数
        int rowNumber = sheet.getPhysicalNumberOfRows();
        //获取列数
        int cellNumber = headers.length;
        for (int m = 1; m < rowNumber; m++) {
            //获取当前行
            Row row = sheet.getRow(m);
            SysUser sysUser = new SysUser();
            for (int n = 0; n < cellNumber; n++) {
                //获取当前行的每一列，就是每一个单元格
                Cell cell = row.getCell(n);
                if (cell!=null){
                    String type = parseCellType(cell);
                    //之后对这个进行读取，每一列就是一个对象
                    switch (headers[n]){
                        case "用户名":
                            if ("STRING".equals(type)){
                                String username = cell.getStringCellValue();
                                List<SysUser> userListByName = userMapper.selectByUserName(username);
                                if (userListByName.size()==0){
                                    sysUser.setUsername(username);
                                }else {
                                    dto.setMsg("第"+(m+1)+"行数据不可重复导入");
                                }
                                break;
                            }else {
                                dto.setMsg("第"+(m+1)+"行用户名类型不符合");
                                break;
                            }
                        case "邮箱":
                            if ("STRING".equals(type)){
                                sysUser.setEmail(cell.getStringCellValue());
                                break;
                            }else {
                                dto.setMsg("第"+(m+1)+"邮箱类型不符合");
                                break;
                            }
                        case "个人描述":
                            if ("STRING".equals(type)){
                                sysUser.setDescription(cell.getStringCellValue());
                                break;
                            }else {
                                dto.setMsg("第"+(m+1)+"个人描述不符合");
                                break;
                            }
                        case "电话号":
                            if ("NUMBER".equals(type)){
                                DataFormatter dataFormatter = new DataFormatter();
                                dataFormatter.addFormat("###########", null);
                                String phone = dataFormatter.formatCellValue(cell);
                                sysUser.setPhone(phone);
                                break;
                            }else {
                                dto.setMsg("第"+(m+1)+"个人描述不符合");
                                break;
                            }
                        case "性别":
                            if ("STRING".equals(type)){
                                String sex = cell.getStringCellValue();
                                if ("男".equals(sex)){
                                    sysUser.setSex(1);
                                }else {
                                    sysUser.setSex(0);
                                }
                                break;
                            }else {
                                dto.setMsg("第"+(m+1)+"个人描述不符合");
                                break;
                            }
                        default:
                            break;
                    }
                }else {
                    if (n == 0){
                        return AjaxResult.error("用户名不能为空");
                    }
                }
            }
            sysUser.setId(UUIDUtils.getUUId());
            sysUser.setPassword("5e15efc6bb4299bc9840a6a43f5346ce");
            sysUser.setType("1");
            userList.add(sysUser);
        }
        dto.setData(userList);
        return dto;
    }

    @Override
    public void lockUserById(String id) {
        userMapper.lockUserById(id);
    }

    @Override
    public List<SysUser> tableList(String username, Integer sex, String emailOrPhone, Long userRoleId) {
        return userMapper.tableList(username,sex,emailOrPhone,userRoleId);
    }

    @Override
    public List<XmSelectData> getRoleXmSelect(String userId) {
        List<XmSelectData> roleXmSelect = userMapper.getRoleXmSelect();
        if (StringUtil.isNotBlank(userId)){
            SysUser sysUser = userMapper.selectById(userId);
            //给用户所属于的角色设置为选中状态
            for (XmSelectData data : roleXmSelect) {
                if (data.getValue().equals(sysUser.getRoleId())){
                    data.setSelected(true);
                }
            }
        }
        XmSelectData xmSelectData = new XmSelectData("全部","0",true,null);
        roleXmSelect.add(0,xmSelectData);
        return roleXmSelect;
    }

    public String parseCellType(Cell cell){
        CellType cellType = cell.getCellType();
        String type = "";
        switch (cellType){
            case STRING:
                type = "STRING";
                break;
            case BOOLEAN:
                type = "BOOLEAN";
                break;
            case BLANK:
                type = "BLANK";
                break;
            case NUMERIC:
                if (HSSFDateUtil.isCellDateFormatted(cell)){
                    type = "TIME";
                    break;
                }else {
                    type = "NUMBER";
                    break;
                }
            default:
                type = "NULL";
        }
        return type;
    }


    @Override
    public Set<String> selectRoleSign(String id) {
        List<SysRole> sysRole = userMapper.selectRoleSignByUserId(id);
        Set<String> permsSet = new HashSet<>();
        for (SysRole role : sysRole) {
            if (role != null){
                permsSet.add(role.getRoleSign());
            }
        }
        return permsSet;
    }

    @Override
    public Set<String> selectPermsByUserId(String id) {
        List<String> perms = menuMapper.selectPermsByUserId(id);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtil.isNotBlank(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }


    @Override
    public void saveUser(SysUser user) {
        user.setId(UUIDUtils.getUUId());
        user.setActive(1);
        user.setNickname("BLOG用户"+ DateFormatUtil.dataToStrLong(new Date()));
        user.setPassword(MD5Util.getMd5(BlogConfig.getOriginalPwd(), BlogConfig.getMd5Key()));
        this.save(user);
    }

}
